package zengyan.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;


import java.util.List;

/**
 * Created by Administrator on 2016/3/13.
 */
public class ViewPagerIndicator extends LinearLayout{

    private Paint mPaint;
    private Path mPath;
    private int mCount;
    private int mTriangleWidth;
    private int mTriangleHeight;
    private static final float RADIO_TRIANGLE_WIDTH=1/9F;
    private final int DIMENSION_TRIANGLE_WIDTH_MAX= (int) (getScreenWidth()/3*RADIO_TRIANGLE_WIDTH);
    private int mInitTranslationX;//初始值偏移量
    private int mInitTranslationY;//初始值偏移量
    private int mTranslationX;/*滚动偏移量*/
    private int mTabVisiableCount;
    private static final int COUNT_DEFAULT_TAB = 2;
    private static final int COLOUR_TEXT_NORMAL=0X77FFFFFF;
    private static final int COLOUR_TEXT_HIGH=0XFFFFFFFF;
    public PageOnchangeListener mListener;
    private List<String> mTitles;
    private ViewPager mViewPager;





    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);

        Log.d("indicator", "indicator !!!");
        Log.d("indicator", "构造方法!!! getchildCount:"+this.getChildCount());

        /*初始化画笔*/
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#ffffff"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setPathEffect(new CornerPathEffect(3));
        /*获取可见tab数量*/
        TypedArray typedarray=context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
//                获取自定义属性  typedarray 是一个属性的容器类的实例
        mTabVisiableCount = typedarray.getInt(R.styleable.ViewPagerIndicator_visible_tab_count, COUNT_DEFAULT_TAB);
        if (mTabVisiableCount < 0) {
            mTabVisiableCount = COUNT_DEFAULT_TAB;
        }
        typedarray.recycle();
        /*缓存一下，然后typedarray就可以复用*/



    }

    public ViewPagerIndicator(Context context) {
        this(context, null);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        Log.d("indicator", "dispatchDraw!!!");
        canvas.save();
        canvas.translate(mInitTranslationX+mTranslationX,-5);
        canvas.drawPath(mPath,mPaint);
        canvas.restore();
        super.dispatchDraw(canvas);
    }
    /*LinearLayout 中当控件发生改变时会调用这个方法*/
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Log.d("indicator", "onSizeChanged!!!"+w+"+"+h+"+"+oldw+"+"+oldh+"+");
        super.onSizeChanged(w, h, oldw, oldh);
        mTriangleWidth = (int)(w /mTabVisiableCount* RADIO_TRIANGLE_WIDTH);
        mTriangleWidth = Math.min(mTriangleWidth, DIMENSION_TRIANGLE_WIDTH_MAX);
        mInitTranslationX=w/mTabVisiableCount/2-mTriangleWidth/2;
        mInitTranslationY=h;
        intiTrangle();


    }
    //初始化三角形
    private void intiTrangle() {
        Log.d("indicator", "intiTrangle!!!");
        mTriangleHeight = mTriangleWidth / 2;
        mPath = new Path();
        mPath.moveTo(0,0);
        mPath.lineTo(mTriangleWidth / 2,mTriangleHeight);
        mPath.lineTo(mTriangleWidth, 0);
        mPath.close();


    }

    @Override
    protected void onFinishInflate() {
        Log.d("indicator", "onFinishInflate!!!");
        super.onFinishInflate();
        int cCount = getChildCount();
        Log.d("indicator", "onFinishInflate getchildCount:"+this.getChildCount());
        if (cCount==0) return;
        Log.d("indicator", "神奇的事情发生了");
        for (int i = 0; i < cCount; i++) {
            Log.d("indicator", "cCount"+cCount);
            TextView view= (TextView) getChildAt(i);
            LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight=0;
            lp.width=getScreenWidth()/mTabVisiableCount;
            view.setAlpha((float) 0.5);
            view.setTextSize(20);
            view.setLayoutParams(lp);
        }

        setItemClickEvent();



    }

    //指示器跟随手指滚动
    public void scroll(int position, float offset) {
        int tabWidth=getWidth()/mTabVisiableCount;
        int moveCount=position - (mTabVisiableCount - 2);

        mTranslationX = (int) (tabWidth * (offset + position));
        if(position>=(mTabVisiableCount-2)&&getChildCount()>mTabVisiableCount){

            if (mTabVisiableCount != 1) {
                this.scrollTo((position - (mTabVisiableCount - 2)) * tabWidth + (int) (tabWidth * offset), 0);
            }else {
                this.scrollTo(position*tabWidth+(int)(tabWidth*offset),0);


            }

        }

        invalidate();
//        刷新view
    }

    /*获得屏幕属性*/
    public int getScreenWidth() {
        int a,b,c;
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        Log.d("getWidth", "wm.getDefaultDisplay:" + wm.getDefaultDisplay());
        DisplayMetrics outMetrics = new DisplayMetrics();
        Log.d("getWidth", "直接outMetrics.widthPiexels:" + outMetrics.widthPixels);

        /*屏幕分辨率类*/
        wm.getDefaultDisplay().getMetrics(outMetrics);
        Log.d("getWidth", "getWidth:" + getWidth());
        a=getWidth();
        b=outMetrics.widthPixels;



        return outMetrics.widthPixels;
    }

    public void setTabItemTitles(List<String> titles){
       if (titles != null&&titles.size()>0) {
           this.removeAllViews();
           mTitles=titles;
           for (String title : mTitles) {
               addView(generateTextView(title));
           }
           mCount=titles.size();
            setItemClickEvent();
       }
   }

    private void highLightTextView(int pos) {
        resetTextViewColor();

        TextView view = (TextView) getChildAt(pos);
        if (view instanceof TextView) {
            view.setTextColor(COLOUR_TEXT_HIGH);

        }


    }

    private void resetTextViewColor(){
        for (int i = 0; i <getChildCount(); i++) {
            TextView view = (TextView) getChildAt(i);
            if (view instanceof TextView) {
                view.setTextColor(COLOUR_TEXT_NORMAL);
            }
        }


    }

    private View generateTextView(String title) {
        TextView view = new TextView(getContext());
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.width=getScreenWidth()/mTabVisiableCount;
        view.setText(title);
        view.setGravity(Gravity.CENTER);
        view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        view.setTextColor(COLOUR_TEXT_NORMAL);
        view.setLayoutParams(lp);


        return view;
    }


    public void setViewPaper(ViewPager viewPaper,int pos){

        mViewPager=viewPaper;
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                position :当前页面，及你点击滑动的页面。positionOffset:当前页面偏移的百分比。positionOffsetPiexels:当前页面偏移的像素位置。

                scroll(position, positionOffset);
                if (mListener != null) {
                    mListener.onPageScrolled(position,positionOffset,positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                if (mListener != null) {
                    mListener.onPageSelected(position);
                }
                highLightTextView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (mListener != null) {
                    mListener.onPageScrollStateChanged(state);
                }

            }
        });
        highLightTextView(pos);
        mViewPager.setCurrentItem(pos);

    }


    public void setVisibleTabCount(int count){
        mTabVisiableCount=count;

    }

    public interface PageOnchangeListener{

        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
        public void onPageSelected(int position);
        public void onPageScrollStateChanged(int state);
    }


    public void setOnPageChangeListener(PageOnchangeListener listener){
        this.mListener=listener;
    }

    private void setItemClickEvent() {
        Log.d("indicator", "setItemClickEvent!!!");
        for (int i = 0; i <this.getChildCount(); i++) {
            Log.d("indicator", "setItemClickEvent!!! getchildCount:"+this.getChildCount());
            final int j=i;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mViewPager.setCurrentItem(j);
                }
            });
        }

    }
}
